package com.gec.zhs.controller;

import com.gec.zhs.entity.config.AppConfig;
import com.gec.zhs.entity.constants.Constants;
import com.gec.zhs.entity.enums.DateTimePatternEnum;
import com.gec.zhs.entity.enums.ResponseCodeEnum;
import com.gec.zhs.entity.vo.ResponseVO;
import com.gec.zhs.exception.BusinessException;
import com.gec.zhs.utils.DateUtil;
import com.gec.zhs.utils.FFmpegUtils;
import com.gec.zhs.utils.StringTools;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * @author zhs
 * @version 1.0
 * @date 2025-02-03
 * @description
 */
@RestController
@RequestMapping("/file")
@Validated
@Slf4j
public class FileController extends ABaseController {
    @Autowired
    private AppConfig appConfig;

    @Autowired
    private FFmpegUtils fFmpegUtils;

    @ApiOperation("图片上传")
    @RequestMapping("/uploadImage")
    public ResponseVO uploadCover(MultipartFile file, Boolean createThumbnail) throws IOException {
        String month = DateUtil.format(new Date(), DateTimePatternEnum.YYYYMM.getPattern());
        String folder = appConfig.getProjectFolder() + Constants.FILE_FOLDER + Constants.FILE_COVER + month;
        File folderFile = new File(folder);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }
        String fileName = file.getOriginalFilename();
        String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
        String realFileName = StringTools.getRandomString(Constants.LENGTH_30) + fileSuffix;
        String filePath = folder + "/" + realFileName;
        file.transferTo(new File(filePath));
        if (createThumbnail) {
            //生成缩略图
            fFmpegUtils.createImageThumbnail(filePath);
        }
        return getSuccessResponseVO(Constants.FILE_COVER + month + "/" + realFileName);
    }


    @ApiOperation("获取图片")
    @RequestMapping("/getResource")
    public void getResource(HttpServletResponse response, String sourceName) {
        if (!StringTools.pathIsOk(sourceName)) {
            throw new BusinessException(ResponseCodeEnum.CODE_603);
        }
        String filenameExtension = StringTools.getFileSuffix(sourceName);
        response.setContentType("image/" + filenameExtension.replace(".", ""));
        response.setHeader("Cache-Control", "max-age=2592000");//缓存一个月
        readFile(response, sourceName);
    }

    protected void readFile(HttpServletResponse response, String filePath) {
        File file = new File(appConfig.getProjectFolder() + Constants.FILE_FOLDER + filePath);
        if (!file.exists()) {
            return;
        }
        long startTime = System.currentTimeMillis();
        try (OutputStream out = response.getOutputStream();
             // 将 FileInputStream 改为 BufferedInputStream
             BufferedInputStream in = new BufferedInputStream(new FileInputStream(file))) {
            byte[] byteData = new byte[1024];
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len);
            }
            out.flush();
        } catch (IOException e) {
            log.error("读取文件异常", e);
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("文件传输完成，耗时: {}ms", endTime - startTime);
        }
    }
}
